package com.resou.reader.view.wave;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;

import java.util.ArrayList;
import java.util.List;

public class WaveHelper {
    private WaveView mWaveView;

    private AnimatorSet mAnimatorSet;

    public boolean isJustCreated = true;

    public WaveHelper(WaveView waveView,float waterLevel) {
        mWaveView = waveView;
        initAnimation(waterLevel);
    }

    public void start() {
        mWaveView.setShowWave(true);
        if (mAnimatorSet != null) {
//            if (mAnimators.contains(mWaterLevelAnim)) {
//                mAnimators.remove(mWaterLevelAnim);
//                mAnimatorSet.playTogether(mAnimators);
//            }
            mAnimatorSet.start();
        }
    }

    private void initAnimation(float waterLevel) {
        List<Animator> animators = new ArrayList<>();

        // 水平动画。
        // 波浪无限。
        ObjectAnimator waveShiftAnim = ObjectAnimator.ofFloat(
                mWaveView, "waveShiftRatio", 0f, 1f);
        waveShiftAnim.setRepeatCount(ValueAnimator.INFINITE);
        waveShiftAnim.setDuration(1000);
        waveShiftAnim.setInterpolator(new LinearInterpolator());
        animators.add(waveShiftAnim);

//        // 垂直动画。
//        // 水位从0增加到WaveView的中心
        ObjectAnimator waterLevelAnim = ObjectAnimator.ofFloat(
                mWaveView, "waterLevelRatio", 0f, waterLevel);
        waterLevelAnim.setDuration(2000);
        waterLevelAnim.setInterpolator(new DecelerateInterpolator());
        animators.add(waterLevelAnim);

//        // 幅度动画。
//        // 波长大，然后变小，反复
//        ObjectAnimator amplitudeAnim = ObjectAnimator.ofFloat(
//                mWaveView, "amplitudeRatio", 0.0001f, 0.05f);
//        amplitudeAnim.setRepeatCount(ValueAnimator.INFINITE);
//        amplitudeAnim.setRepeatMode(ValueAnimator.REVERSE);
//        amplitudeAnim.setDuration(5000);
//        amplitudeAnim.setInterpolator(new LinearInterpolator());
//        animators.add(amplitudeAnim);

        mAnimatorSet = new AnimatorSet();
        mAnimatorSet.playTogether(animators);
    }

    public void cancel() {
        if (mAnimatorSet != null) {
//            mAnimatorSet.cancel();
            mAnimatorSet.end();
        }
    }
}
